package com.ruoyi.web.controller.checksystem;

import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.checksystem.domain.RechargeRecord;
import com.ruoyi.checksystem.service.IRechargeRecordService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Calendar;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.checksystem.domain.VipPackage;
import com.ruoyi.checksystem.service.IVipPackageService;

/**
 * 充值记录Controller
 * 
 * @author ruoyi
 * @date 2025-03-21
 */
@RestController
@RequestMapping("/checksystem/record")
public class RechargeRecordController extends BaseController
{
    private static final Logger log = LoggerFactory.getLogger(RechargeRecordController.class);

    @Autowired
    private IRechargeRecordService rechargeRecordService;

    @Autowired
    private IVipPackageService vipPackageService;

    /**
     * 查询充值记录列表
     */
    @PreAuthorize("@ss.hasPermi('checksystem:record:list')")
    @GetMapping("/list")
    public TableDataInfo list(RechargeRecord rechargeRecord)
    {
        startPage();
        List<RechargeRecord> list = rechargeRecordService.selectRechargeRecordList(rechargeRecord);
        return getDataTable(list);
    }

    /**
     * 导出充值记录列表
     */
    @PreAuthorize("@ss.hasPermi('checksystem:record:export')")
    @Log(title = "充值记录", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, RechargeRecord rechargeRecord)
    {
        List<RechargeRecord> list = rechargeRecordService.selectRechargeRecordList(rechargeRecord);
        ExcelUtil<RechargeRecord> util = new ExcelUtil<RechargeRecord>(RechargeRecord.class);
        util.exportExcel(response, list, "充值记录数据");
    }

    /**
     * 获取充值记录详细信息
     */
    @PreAuthorize("@ss.hasPermi('checksystem:record:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(rechargeRecordService.selectRechargeRecordById(id));
    }

    /**
     * 新增充值记录
     */
    @PreAuthorize("@ss.hasPermi('checksystem:record:add')")
    @Log(title = "充值记录", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody RechargeRecord rechargeRecord)
    {
        try {
            // 检查是否传入了到期时间(updateTime)，如果没有则需要计算
            if (rechargeRecord.getUpdateTime() == null) {
                log.info("充值记录未设置到期时间，将根据套餐详情计算");
                
                // 解析套餐详情JSON获取充值天数
                String packageDetails = rechargeRecord.getPackageDetails();
                int durationDays = 0;
                
                if (StringUtils.isNotEmpty(packageDetails)) {
                    try {
                        // 使用正则表达式提取duration字段
                        Pattern pattern = Pattern.compile("\"duration\"\\s*:\\s*\"([^\"]+)\"");
                        Matcher matcher = pattern.matcher(packageDetails);
                        if (matcher.find()) {
                            String durationStr = matcher.group(1);
                            
                            if (StringUtils.isNotEmpty(durationStr)) {
                                // 提取数字部分
                                String daysStr = durationStr.replaceAll("[^0-9]", "");
                                if (StringUtils.isNotEmpty(daysStr)) {
                                    durationDays = Integer.parseInt(daysStr);
                                }
                            }
                        }
                    } catch (Exception e) {
                        log.error("解析套餐详情JSON失败", e);
                    }
                }
                
                // 如果无法从套餐详情中获取到天数，则默认为30天
                if (durationDays <= 0) {
                    durationDays = 30;
                    log.info("无法从套餐详情中获取充值天数，使用默认值：{} 天", durationDays);
                } else {
                    log.info("从套餐详情中提取的充值天数: {} 天", durationDays);
                }
                
                // 查询该用户最新的VIP套餐信息
                Date baseTime = new Date(); // 默认使用当前时间
                Long userId = rechargeRecord.getUserId();
                
                if (userId != null) {
                    VipPackage existingPackage = vipPackageService.getUserLatestPackage(userId);
                    if (existingPackage != null && existingPackage.getEndTime() != null) {
                        // 如果用户有未过期的套餐，则基于其到期时间计算新的到期时间
                        Date endTime = existingPackage.getEndTime();
                        if (endTime.after(baseTime)) {
                            baseTime = endTime;
                            log.info("用户有未过期的套餐，使用现有到期时间作为基准时间：{}", baseTime);
                        } else {
                            log.info("用户套餐已过期，使用当前时间作为基准时间：{}", baseTime);
                        }
                    } else {
                        log.info("未找到用户套餐信息，使用当前时间作为基准时间：{}", baseTime);
                    }
                }
                
                // 计算新的到期时间
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(baseTime);
                calendar.add(Calendar.DAY_OF_MONTH, durationDays);
                Date newUpdateTime = calendar.getTime();
                
                // 设置计算后的到期时间
                rechargeRecord.setUpdateTime(newUpdateTime);
                log.info("计算的到期时间为：{}", newUpdateTime);
            }
            
            return toAjax(rechargeRecordService.insertRechargeRecord(rechargeRecord));
        } catch (Exception e) {
            log.error("添加充值记录失败", e);
            return AjaxResult.error("添加充值记录失败: " + e.getMessage());
        }
    }

    /**
     * 修改充值记录
     */
    @PreAuthorize("@ss.hasPermi('checksystem:record:edit')")
    @Log(title = "充值记录", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody RechargeRecord rechargeRecord)
    {
        log.info("修改充值记录: {}", rechargeRecord);
        
        // 处理packageDetails，确保只包含三个必要字段
        if (rechargeRecord.getPackageDetails() != null) {
            try {
                String packageDetailsStr = rechargeRecord.getPackageDetails();
                if (packageDetailsStr.startsWith("{") && packageDetailsStr.endsWith("}")) {
                    // 提取三个关键字段
                    Integer price = null;
                    Integer points = null;
                    String duration = null;
                    
                    // 提取price
                    int priceIdx = packageDetailsStr.indexOf("\"price\"");
                    if (priceIdx > 0) {
                        int colonIdx = packageDetailsStr.indexOf(":", priceIdx);
                        if (colonIdx > 0) {
                            int commaIdx = packageDetailsStr.indexOf(",", colonIdx);
                            if (commaIdx > 0) {
                                String priceStr = packageDetailsStr.substring(colonIdx + 1, commaIdx).trim();
                                try {
                                    price = Integer.parseInt(priceStr);
                                } catch (NumberFormatException e) {
                                    log.warn("无法解析价格: " + priceStr);
                                }
                            }
                        }
                    }
                    
                    // 提取points
                    int pointsIdx = packageDetailsStr.indexOf("\"points\"");
                    if (pointsIdx > 0) {
                        int colonIdx = packageDetailsStr.indexOf(":", pointsIdx);
                        if (colonIdx > 0) {
                            int commaIdx = packageDetailsStr.indexOf(",", colonIdx);
                            if (commaIdx > 0) {
                                String pointsStr = packageDetailsStr.substring(colonIdx + 1, commaIdx).trim();
                                try {
                                    points = Integer.parseInt(pointsStr);
                                } catch (NumberFormatException e) {
                                    log.warn("无法解析点数: " + pointsStr);
                                }
                            } else {
                                // 可能是最后一个字段
                                int braceIdx = packageDetailsStr.indexOf("}", colonIdx);
                                if (braceIdx > 0) {
                                    String pointsStr = packageDetailsStr.substring(colonIdx + 1, braceIdx).trim();
                                    try {
                                        points = Integer.parseInt(pointsStr);
                                    } catch (NumberFormatException e) {
                                        log.warn("无法解析点数: " + pointsStr);
                                    }
                                }
                            }
                        }
                    }
                    
                    // 提取duration
                    int durationIdx = packageDetailsStr.indexOf("\"duration\"");
                    if (durationIdx > 0) {
                        int colonIdx = packageDetailsStr.indexOf(":", durationIdx);
                        if (colonIdx > 0) {
                            int valueStart = packageDetailsStr.indexOf("\"", colonIdx);
                            if (valueStart > 0) {
                                int valueEnd = packageDetailsStr.indexOf("\"", valueStart + 1);
                                if (valueEnd > 0) {
                                    duration = packageDetailsStr.substring(valueStart + 1, valueEnd);
                                }
                            }
                        }
                    }
                    
                    // 重新构建简化版packageDetails
                    if (price != null && points != null && duration != null) {
                        String newPackageDetails = String.format("{\"price\": %d, \"points\": %d, \"duration\": \"%s\"}", 
                            price, points, duration);
                        rechargeRecord.setPackageDetails(newPackageDetails);
                        log.info("简化后的套餐详情: " + newPackageDetails);
                    }
                    
                    // 计算到期时间
                    if (rechargeRecord.getUpdateTime() == null && duration != null) {
                        // 提取天数
                        int days = 30; // 默认30天
                        if (duration.contains("天")) {
                            String numStr = duration.substring(0, duration.indexOf("天"));
                            try {
                                days = Integer.parseInt(numStr);
                            } catch (NumberFormatException e) {
                                log.warn("无法解析天数: " + numStr + ", 使用默认值30天");
                            }
                        } else {
                            try {
                                days = Integer.parseInt(duration);
                            } catch (NumberFormatException e) {
                                log.warn("无法解析天数: " + duration + ", 使用默认值30天");
                            }
                        }
                        
                        // 计算到期时间
                        Date baseDate = rechargeRecord.getTransferTime() != null ? 
                                        rechargeRecord.getTransferTime() : new Date();
                        Calendar calendar = Calendar.getInstance();
                        calendar.setTime(baseDate);
                        calendar.add(Calendar.DAY_OF_MONTH, days);
                        rechargeRecord.setUpdateTime(calendar.getTime());
                        log.info("计算的到期时间: " + rechargeRecord.getUpdateTime());
                    }
                }
            } catch (Exception e) {
                log.error("处理packageDetails失败", e);
            }
        }
        
        return toAjax(rechargeRecordService.updateRechargeRecord(rechargeRecord));
    }

    /**
     * 删除充值记录
     */
    @PreAuthorize("@ss.hasPermi('checksystem:record:remove')")
    @Log(title = "充值记录", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(rechargeRecordService.deleteRechargeRecordByIds(ids));
    }
}
